import { defineStore } from 'pinia'
import axios from '@/utils/axios'
import config from '@/config/config'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    accessToken: "",
    refreshToken: "",
  }),
  actions: {
    async login(email, password) {
      const response = await axios.post(`${config.getServerUrl()}/api/users/login`, { email, password })
      this.accessToken = response.data.access_token
      this.refreshToken = response.data.refresh_token
    },
    async refreshAccessToken() {
      const response = await axios.post(`${config.getServerUrl()}/api/users/refresh`, { refresh_token: this.refreshToken })
      this.accessToken = response.data.access_token
    },
    async verifyToken() {
      const response = await axios.get(`${config.getServerUrl()}/api/users/me`, { headers: { Authorization: `Bearer ${this.accessToken}` } })
      if (response.status === 200) {
        return true
      } else {
        this.accessToken = ""
        return false
      }
    },
  },
})
